package com.kws.system.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.kws.system.api.domain.SysRole;
import com.kws.system.domain.SysMenu;
import com.kws.system.domain.info.QueryMenuInfo;
import com.kws.system.domain.info.QueryMenuTreeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.kws.common.core.constant.UserConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.service.ISysMenuService;
import com.kws.system.service.ISysPermissionService;
import com.kws.system.service.ISysRoleService;

/**
 * 用户权限处理
 * 
 * @author zhangyh
 */
@Service
public class SysPermissionServiceImpl implements ISysPermissionService
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取角色数据权限
     * 
     * @param userId 用户Id
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(SysUser user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param userId 用户Id
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    if (StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL))
                    {
                        Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                        role.setPermissions(rolePerms);
                        perms.addAll(rolePerms);
                    }
                }
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }

    @Override
    public QueryMenuInfo queryMenuByRoleId(SysUser user) {
        QueryMenuInfo info = new QueryMenuInfo();
        //查询关联角色
        List<Long> menuIdList = roleService.queryRoleByUserId(user.getUserId());
        if (CollectionUtil.isNotEmpty(menuIdList)){
            List<Long> menuIds = menuIdList.stream().distinct().collect(Collectors.toList());
            //查询所有角色关联菜单
            //查询后台管理系统菜单权限
            SysMenu menu = menuService.selectMenuById(1067l);
            List<SysMenu> resultMenuList = new ArrayList();
            resultMenuList.add(menu);
            getMenuById(menuIds,resultMenuList);
            info.setBackgroundManagementList(resultMenuList);
            //查询物联网管理系统菜单权限
            SysMenu internetThingMenu = menuService.selectMenuById(1068l);
            List<SysMenu> internetThingMenuList = new ArrayList();
            internetThingMenuList.add(internetThingMenu);
            getMenuById(menuIds,internetThingMenuList);
            info.setInternetThingList(internetThingMenuList);
            //查询商家服务系统菜单权限
            SysMenu merchantServiceMenu = menuService.selectMenuById(1070l);
            List<SysMenu> merchantServiceMenuList = new ArrayList();
            merchantServiceMenuList.add(merchantServiceMenu);
            getMenuById(menuIds,merchantServiceMenuList);
            info.setMerchantServiceList(merchantServiceMenuList);
            //查询用户服务系统菜单权限
            SysMenu userServiceMenu = menuService.selectMenuById(1071l);
            List<SysMenu> userServiceMenuList = new ArrayList();
            userServiceMenuList.add(userServiceMenu);
            getMenuById(menuIds,userServiceMenuList);
            info.setUserServiceList(userServiceMenuList);
            //微网管理系统菜单权限
            SysMenu microgridManagementMenu = menuService.selectMenuById(1074l);
            List<SysMenu> microgridManagementMenuList = new ArrayList();
            microgridManagementMenuList.add(microgridManagementMenu);
            getMenuById(menuIds,microgridManagementMenuList);
            info.setMicrogridManagementList(microgridManagementMenuList);
            //用户服务系统APP端菜单权限
            SysMenu userServiceAppMenu = menuService.selectMenuById(1072l);
            List<SysMenu> userServiceAppMenuList = new ArrayList();
            userServiceAppMenuList.add(userServiceAppMenu);
            getMenuById(menuIds,userServiceAppMenuList);
            info.setUserServiceAppList(userServiceAppMenuList);
            //商家服务系统APP端菜单权限
            SysMenu merchantServiceAppMenu = menuService.selectMenuById(1073l);
            List<SysMenu> merchantServiceAppMenuList = new ArrayList();
            merchantServiceAppMenuList.add(merchantServiceAppMenu);
            getMenuById(menuIds,merchantServiceAppMenuList);
            info.setMerchantServiceAppList(merchantServiceAppMenuList);
        }
        return info;
    }

    public void getMenuById(List<Long> menuIds,List<SysMenu> menuList){
        if (CollectionUtil.isNotEmpty(menuList)){
            menuList.forEach(item -> {
                List<SysMenu> list = menuService.queryMenuByParentId(menuIds,item.getMenuId());
                if (CollectionUtil.isEmpty(list)){
                    return;
                }
                item.setChildren(list);
                getMenuById(menuIds,list);
            });
        }
    }
}
